<template>
  <div>
    <div class="container">
      <template v-if="isChart">
        <div class="handle-box">
          <span>台区名称：</span>
          <el-input
            v-model="query.districtName"
            placeholder="请输入台区名称"
            class="handle-input mr10"
          ></el-input>

          <el-button type="default" @click="reset">重置</el-button>
          <el-button type="primary" :icon="Search" @click="handleSearch"
            >搜索</el-button
          >
          <el-button type="primary" :icon="Plus" @click="handleCreate"
            >创建一个台区拓扑</el-button
          >
        </div>
        <el-table
          :height="tableHeight"
          :data="tableData"
          v-loading="homeLoading"
          border
          class="table"
          ref="multipleTable"
          header-cell-class-name="table-header"
        >
          <el-table-column width="100" align="center" label="序号" fixed>
            <template v-slot="scope">
              {{ indexMethod(scope.$index, query.pageIndex, query.pageSize) }}
            </template>
          </el-table-column>
          <el-table-column prop="districtName" label="台区名称" align="center">
            <template v-slot="scope">
              <span
                style="color: blue; cursor: pointer; text-decoration: underline"
                @click="showDisTree(scope.row)"
                >{{ scope.row.districtName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="curMeteringCycle"
            label="当前计量周期"
            align="center"
          ></el-table-column>
          <el-table-column prop="curStatus" label="当前状态" align="center">
          </el-table-column>
          <el-table-column
            prop="onlineNum"
            align="center"
            label="当前在线设备数量"
          >
          </el-table-column>
          <el-table-column
            prop="heartbeatTime"
            label="累计监测时长（天）"
            align="center"
          ></el-table-column>
          <el-table-column label="操作" width="300" align="center">
            <template #default="scope">
              <el-button type="primary" plain @click="showModal(scope.row)">
                导入电表计量数据
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="查看台区线损走势图" align="center">
            <template #default="scope">
              <el-button type="primary" @click="lineDetail(scope.row)">
                点击查看
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-popconfirm @confirm="deleteTQ(scope.row)" title="确定删除吗?">
                <template #reference>
                  <el-button type="danger"> 删除 </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            layout="total, prev, pager, next"
            :current-page="query.pageIndex"
            :page-size="query.pageSize"
            :total="pageTotal"
            @current-change="handlePageChange"
          ></el-pagination>
        </div>
      </template>
      <div v-else>
        <el-button
          style="width: 200px; margin-bottom: 50px"
          type="primary"
          @click="isChart = !isChart"
          >返回</el-button
        >
        <LineChart :data="currentLineData" />
      </div>
    </div>

    <el-dialog
      top="15vh"
      width="1000px"
      v-model="listVisible"
      custom-class="dialogClass"
      :close-on-click-modal="false"
    >
      <template #title>
        <div style="display: flex">
          <span style="font-size: 18px; margin-right: 16px">{{
            currentDataItem.districtName
          }}</span>
          <el-upload
            style="width: 100px; height: 40px"
            multiple
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
            :limit="1"
          >
            <el-button type="primary">导入最新数据</el-button>
          </el-upload>
        </div>
      </template>
      <el-table
        :data="TcpData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <el-table-column width="100" align="center" label="序号" fixed>
          <template v-slot="scope">
            {{ indexMethod(scope.$index, query.pageIndex, query.pageSize) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="importTime"
          label="导入日期"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="fileName"
          label="文件名称"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="importMeteringTime"
          label="导入数据的计量时间"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column label="查看台区线损走势图" align="center">
          <template #default="scope">
            <a
              v-if="scope.row.fileUrl"
              :href="scope.row.fileUrl"
              target="_blank"
              >下载</a
            >
            <!-- <el-button type="primary" @click="getTcpChart(scope.row)">
              下载
            </el-button> -->
          </template>
        </el-table-column>
        <!-- <el-table-column prop="oneChannelAccumulatedPower" label="A相累计电量" align="center" width="160"></el-table-column> -->
      </el-table>
      <el-pagination
        small
        layout="prev, pager, next"
        @current-change="changeTpcList"
        :total="queryTcp.total"
      >
      </el-pagination>
    </el-dialog>

    <el-dialog
      top="15vh"
      width="480px"
      v-model="createVisible"
      custom-class="dialogClass"
      :close-on-click-modal="false"
      :title="`${isEditTQ ? '修改' : '创建'}一个台区拓扑`"
    >
      <div
        style="
          display: flex;
          align-items: center;
          position: absolute;
          right: 50px;
          top: 55px;
        "
      >
        <img
          style="width: 25px"
          src="../../../assets/img/electricDevice.png"
          alt=""
        />: 电表
        <img
          style="width: 20px; margin-left: 10px; margin-right: 3px"
          src="../../../assets/img/normalDevice.png"
          alt=""
        />
        : 监测设备
      </div>
      <el-tree
        :data="dataSource"
        show-checkbox
        node-key="deviceNo"
        default-expand-all
        :expand-on-click-node="false"
        :props="{
          label: 'deviceNo',
          children: 'child'
        }"
      >
        <template #default="{ node, data }">
          <span
            class="custom-tree-node"
            style="display: flex; align-items: center"
          >
            <span style="margin-right: 6px">{{ data.deviceNo }}</span>
            <img
              v-if="data.deviceType === 0"
              src="../../../assets/img/electricDevice.png"
              class="electric-icon"
              alt=""
            />
            <img
              v-else-if="data.deviceType === 1"
              src="../../../assets/img/normalDevice.png"
              alt=""
            />

            <span class="tree-node-icon">
              <el-icon :size="22" @click="treeAppend(node, data)"
                ><Plus
              /></el-icon>
              <el-icon
                :size="22"
                style="margin-left: 8px"
                @click="remove(node, data)"
                ><Delete
              /></el-icon>
              <el-icon
                :size="22"
                style="margin-left: 8px"
                @click="edit(node, data)"
                ><Edit
              /></el-icon>
              <img
                @click="bindIcon(0, node, data)"
                src="../../../assets/img/electricDevice.png"
                class="electric-icon"
                alt=""
              />
              <img
                @click="bindIcon(1, node, data)"
                src="../../../assets/img/normalDevice.png"
                alt=""
              />
              <!-- <a @click="treeAppend(node, data)"> Append </a>
              <a style="margin-left: 8px" @click="remove(node, data)">
                Delete
              </a>
              <a style="margin-left: 8px" @click="edit(node, data)"> Edit </a> -->
            </span>
          </span>
        </template>
      </el-tree>

      <div style="text-align: right; margin-top: 20px">
        <el-button @click="createVisible = false">取消</el-button>
        <el-button @click="createConfirm">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      top="25vh"
      width="360px"
      v-model="editVisible"
      custom-class="dialogClass"
      :close-on-click-modal="false"
      :title="`修改${dialogTitle}`"
    >
      <el-form>
        <el-form-item :label="dialogTitle">
          <el-input v-model="editValue" style="width: 200px"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="editConfirm">确认</el-button>
      </template>
    </el-dialog>

    <el-dialog
      top="25vh"
      width="400px"
      v-model="disTreeVisible"
      custom-class="dialogClass"
      :title="`查看台区树`"
    >
      <template #title>
        <div style="display: flex; align-items: center">
          查看树
          <el-button type="primary" style="margin-left: 8px" @click="editTQName"
            >修改台区名称</el-button
          >
        </div>
      </template>
      <div style="min-height: 200px">
        <el-tree
          :data="disTreeData"
          :props="{
            label: 'deviceNo',
            children: 'children'
          }"
          :default-expand-all="true"
        />
      </div>
    </el-dialog>

    <el-dialog
      top="25vh"
      width="400px"
      v-model="changeNameVisible"
      custom-class="dialogClass"
      :title="`修改台区名称`"
    >
      <div style="min-height: 80px">
        <el-form>
          <el-form-item label="台区名称">
            <el-input v-model="editTQNameValue" style="width: 200px"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="changeNameVisible = false">取消</el-button>
        <el-button type="primary" @click="editTQNameConfirm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive } from "vue"
import LineChart from "./lineChart.vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { View, Search, Delete, Edit, Plus } from "@element-plus/icons-vue"
import {
  getOnlneList,
  getDevice,
  createDevice,
  deleteDevice,
  editDevice,
  TcpList,
  TcpChart,
  getNewDeviceList,
  createNewDistrict,
  getNewImportFileList,
  baseURl,
  uploadNewFile,
  getNewTree,
  editNewDistrict,
  deleteNewDistrict
} from "../../../api/index"
import { indexMethod, getViewPortHeight } from "../../../utils/tools"
// import { initChart } from "./CreateEchar";

const isChart = ref(true)

const myChart = ref(null)
const tableHeight = getViewPortHeight() - 320
interface TableItem {
  id: number
  name: string
  money: string
  state: string
  date: string
  address: string
}

const query = reactive({
  districtName: "",
  pageIndex: 1,
  pageSize: 10
})
const queryTcp = reactive({
  pageNumber: 1,
  pageSize: 10,
  total: 0,
  deviceNo: null,
  passNo: "0",
  measurementStartTime: null,
  measurementEndTime: null,
  time: null
})
const queryCharts = reactive({
  endDate: null,
  passNo: "0",
  startDate: null,
  deviceNo: null,
  time: null
})

const homeLoading = ref(true)
const tableData = ref<TableItem[]>([])
const TcpData = ref<TableItem[]>([])
const pageTotal = ref(0)
// 获取表格数据
const getData = async () => {
  homeLoading.value = true
  const res = await getNewDeviceList({
    districtName: query.districtName,
    pageNumber: query.pageIndex,
    pageSize: query.pageSize
  })
  homeLoading.value = false
  tableData.value = res.rows
  pageTotal.value = res.total || 0
}
getData()

const getTcp = async () => {
  const res = await getNewImportFileList({
    pageNumber: queryTcp.pageNumber,
    pageSize: queryTcp.pageSize,
    districtId: currentDataItem.value.districtId
  })
  TcpData.value = res.rows
  queryTcp.total = res.total
}
// 查询操作
const reset = () => {
  query.pageIndex = 1
  query.districtName = ""
  getData()
}
const handleSearch = () => {
  query.pageIndex = 1
  getData()
}

const dialogTitle = ref("")
const dataSource = ref([
  {
    deviceNo: "未知台区",
    parentId: "",
    child: []
  }
])

const treeAppend = (currentNode, data) => {
  const item = {
    deviceNo: "未知设备",
    parentId: data.deviceNo,
    child: []
  }
  data.child.push(item)
  dataSource.value = [...dataSource.value]
}

const editValue = ref("")
const currentEditItem = ref("")
const edit = (node, data) => {
  if (Number(data.parentId) > 0) {
    dialogTitle.value = "设备ID"
  } else {
    dialogTitle.value = "台区名称"
  }
  currentEditItem.value = data
  editVisible.value = true
  editValue.value = data.deviceNo
}
const remove = (node, data) => {
  const parent = node.parent
  const child = parent.data.child || parent.data
  const index = child.findIndex((d) => d.deviceNo === data.deviceNo)
  child.splice(index, 1)
  dataSource.value = [...dataSource.value]
}
const bindIcon = (type, node, data) => {
  console.log(type, node, data)
  data.deviceType = type
  dataSource.value = [...dataSource.value]
}
const editConfirm = () => {
  if (currentEditItem.value.child.length) {
    currentEditItem.value.child.forEach(
      (item) => (item.parentId = editValue.value)
    )
  }
  currentEditItem.value.deviceNo = editValue.value
  dataSource.value = [...dataSource.value]
  editVisible.value = false
}

const isEditTQ = ref(false)
const createVisible = ref(false)
const handleCreate = () => {
  createVisible.value = true
  isEditTQ.value = false

  dataSource.value = [
    {
      deviceNo: "未知台区",
      parentId: "-1",
      child: []
    }
  ]
}
const createConfirm = async () => {
  const data = dataSource.value
  // if(isEditTQ.value){

  // }
  data[0].districtName = data[0].deviceNo
  delete data[0].deviceNo

  const finalData = data[0]
  console.log(data[0])
  if (isEditTQ.value) {
    const res = await editNewDistrict(finalData)
    ElMessage.success("修改成功！")
    getData()
    createVisible.value = false
    return
  }
  const res = await createNewDistrict(finalData)
  if (res) {
    ElMessage.success("添加成功！")
    getData()
    createVisible.value = false
  }
}
// 分页导航
const handlePageChange = (val: number) => {
  query.pageIndex = val
  getData()
}
// Tpc列表分页
const changeTpcList = (val: number) => {
  queryTcp.pageNumber = val
  getTcp()
}
const chartVisible = ref(false)
const tipBoolen = ref(false)
// Tpc折线图
const getTcpChart = (val: any) => {
  let tiem1 = null
  let tiem2 = null
  if (val.deviceNo) {
    queryCharts.deviceNo = val.deviceNo
  }
  chartVisible.value = true
  TcpChart({
    deviceNo: queryCharts.deviceNo,
    endDate: tiem2,
    passNo: queryCharts.passNo,
    startDate: tiem1
  }).then((val: any) => {
    const arr: any = [0]
    const titel: any = [""]
    tipBoolen.value = Boolean(val.rows.length)

    val.rows.forEach((item: any) => {
      arr.push(item.total)
      titel.push(item.dataTime)
    })
    // initChart(arr, titel);
  })
}

// 表格编辑时弹窗和保存
const editVisible = ref(false)
let form = reactive({
  name: "",
  address: "",
  deviceNo: "",
  electricNo: "",
  id: "",
  passNo: "",
  testNo: ""
})
const visibleType = ref("add")

const currentDataItem = ref("")
const listVisible = ref(false)
const showModal = (item) => {
  listVisible.value = true
  currentDataItem.value = item
  getTcp()
}

const currentLineData = ref("")
const lineDetail = (item) => {
  isChart.value = false
  currentLineData.value = item
}
const handleSuccess = () => {
  ElMessage.success("上传成功")
}
const handleError = () => {
  ElMessage.error("上传失败,请重新上传")
}
const beforeUpload = async (file) => {
  const formData = new FormData()
  formData.append("file", file)
  formData.append("districtId", currentDataItem.value.districtId)
  const res = await uploadNewFile(formData)
  if (res.code == 200) {
    ElMessage.success("上传成功")
    getTcp()
  }
  return false
}

const disTreeVisible = ref(false)
const disTreeData = ref([])
const currentEditNameItem = ref("")

const showDisTree = async (row) => {
  createVisible.value = true
  isEditTQ.value = true
  // disTreeVisible.value = true;
  currentEditNameItem.value = row
  const res = await getNewTree(row.districtId)

  if (res.rows.districtId) {
    res.rows.deviceNo = res.rows.districtName
    // disTreeData.value = [res.rows];
    dataSource.value = [res.rows]
  } else {
    // disTreeData.value = [];
    dataSource.value = []
  }
}

const changeNameVisible = ref(false)
const editTQNameValue = ref("")
const editTQName = () => {
  // currentEditNameItem.value row
  editTQNameValue.value = currentEditNameItem.value.districtName
  changeNameVisible.value = true
}
const editTQNameConfirm = () => {
  const districtId = currentEditNameItem.value.districtId
  console.log(currentEditNameItem.value)
  // const res = await getNewTree(row.districtId);
}

const deleteTQ = async (row) => {
  const res = await deleteNewDistrict(row.districtId)
  if (res) {
    ElMessage.success("删除成功")
    getData()
  }
  console.log(row)
}
</script>
<style scoped lang="less">
.custom-tree-node {
  display: block;

  img {
    width: 20px;
    // height: 24px;
    margin-left: 8px;
    &.electric-icon {
      width: 26px;
    }
  }
  & > img {
  }
  .tree-node-icon {
    opacity: 0;
    transition: all 0.3s;
    margin-left: 40px;
    display: flex;
    align-items: center;
  }
  &:hover {
    .tree-node-icon {
      opacity: 1;
    }
  }
}

:deep(.el-upload--text) {
  width: auto;
  height: auto;
  border: none;
}
</style>
